package controller

import (
	"bytes"
	"encoding/json"
	bc "financial/application/blockchain"
	"financial/application/lib"
	"financial/application/util"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func CreateVacuna(ctx *gin.Context)  {
	req := new(lib.Vacuna)
	if err := ctx.ShouldBind(req); err != nil {
		_ = ctx.AbortWithError(http.StatusBadRequest, err)
		return
	}

	req.Id = util.Krand(11, 0)
	req.FechaDeproducción = time.Now()
	marshal, _ := json.Marshal(req)
	resp, err := bc.ChannelExecute("createVacuna", [][]byte{
		marshal,
	})
	if err != nil {
		fmt.Println("ERROR: ", err.Error())
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}
	ctx.JSON(http.StatusOK, resp)
}

func CreateOrder(ctx *gin.Context)  {
	req := new(lib.VacunaTransaction)
	if err := ctx.ShouldBind(req); err != nil {
		_ = ctx.AbortWithError(http.StatusBadRequest, err)
		return
	}
	req.Id = util.Krand(11, 0)
	marshal, _ := json.Marshal(req)
	resp, err := bc.ChannelExecute("createOrder", [][]byte{
		marshal,
	})
	if err != nil {
		fmt.Println("ERROR: ", err.Error())
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}
	ctx.JSON(http.StatusOK, resp)
}

func QueryRoleVacunas(ctx *gin.Context)  {
	id := ctx.Param("id")
	resp, err := bc.ChannelExecute("queryRoleVacunas", [][]byte{
		[]byte(id),
	})
	if err != nil {
		fmt.Println("ERROR: ", err.Error())
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}
	ctx.String(http.StatusOK, bytes.NewBuffer(resp.Payload).String())
}